package com.tech.security.securityservice.util;

import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ReactiveRedisOperations;

import java.util.Date;
import java.util.Map;

/**
 * @author sl
 */
@Slf4j
public class JwtTokenUtils {


    /**
     * 额外的数据，越复杂越安全
     */
    private static final String SING_VALUE = "dsdadfsghkjlsdfnmkjsd";

    /**
     * 过期时间
     */
    private static ReactiveRedisOperations<Object, Object> redisTemplate;


    public static String getJwtToken(String id){

        String JwtToken = JWT.create()
                .withClaim("userId",id)
                .withExpiresAt(DateUtil.offsetHour(new Date(),1))
                .sign(Algorithm.HMAC256(SING_VALUE));

        return JwtToken;
    }

    public static boolean CheckToken(String token){
        try {
            JWT.require(Algorithm.HMAC256(SING_VALUE)).build().verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    public static String parseTokenInfo(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SING_VALUE)).build().verify(token);

        Claim claim = verify.getClaim("userId");

        return claim.asString();
    }
}
